import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios';
import { catchError, firstValueFrom, throwError } from 'rxjs';

@Injectable()
export class TranslateService {
  constructor(
    private configService: ConfigService,
    private readonly httpService: HttpService,
  ) {}

  public async translate(data: string[]): Promise<string[]> {
    const { key, region } = this.configService.get('translator');

    return new Promise(async (resolve, reject) => {
      try {
        const response = await firstValueFrom(
          this.httpService
            .post(
              'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=en-us',
              data.map((item) => ({ Text: item })),
              {
                headers: {
                  'Ocp-Apim-Subscription-Key': key,
                  'Content-Type': 'application/json',
                  'Ocp-Apim-Subscription-Region': region,
                },
              },
            )
            .pipe(
              catchError((error: any) => {
                console.error('Error occurred while translating:', error);
                reject(error);
                return throwError(() => error);
              }),
            ),
        );
        resolve(
          response.data[0].translations.map(
            (item: { text: string }) => item.text,
          ),
        );
      } catch (err) {
        reject('microsofttranslator 401');
      }
    });
  }
}
